package com.huwei.modules.base.controller.valid;

import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import com.huwei.modules.base.constant.JsonResultConstant;

import lombok.extern.slf4j.Slf4j;


/**
 * Controller 全局处理类
 * 若需要针对某一类或某一个controller处理，请设置@ControllerAdvice
 */
@Slf4j
@ResponseBody
@ControllerAdvice()
public class GlobalExceptionHandler {

	/**
	 * 未知异常处理
	 */
	@ExceptionHandler(Throwable.class)
	public JsonResultConstant unknow(Throwable e) {
		log.error("---> 服务器错误，未知异常：" + e.getMessage(),e);
		//email到管理员
		return JsonResultConstant.create(599, e.getMessage());
	}
	/**
	 * 请求参数错误处理
	 */
	@ExceptionHandler(RequestParamterError.class)
	public JsonResultConstant requestParamterError(HttpServletRequest request ,HttpServletResponse response ,RequestParamterError e) {
		StringBuffer msg = new StringBuffer("参数错误");
		Errors errors = e.getError();
		if(errors.hasErrors()) {
			msg.append(": ");
			List<FieldError> fieldErrors = errors.getFieldErrors();
			for(int i = 0 ,len = fieldErrors.size() ;i < len ;++i) {
				FieldError fe = fieldErrors.get(i);
				String message = fe.getDefaultMessage();
				String fieldName = fe.getField();
				msg.append("参数-").append(fieldName).append("=>").append(Objects.isNull(message)?"缺少或错误":message).append(";");
			}
		}
		log.info("---> 请求参数错误： " +msg.toString());
		return JsonResultConstant.create(600, msg.toString());
	}
	/**
	 * 业务中断异常处理
	 */
	@ExceptionHandler(ServiceInterruptionException.class)
	public JsonResultConstant ServiceInterruptionException(ServiceInterruptionException ex) {
		log.info("---> 业务中断：" + ex.getMessage());
		return JsonResultConstant.create(ex.getCode(), ex.getMessage());
	}
	/**
	 * 缺少请求参数处理
	 */
	@ExceptionHandler(MissingServletRequestParameterException.class)
	public JsonResultConstant missingServletRequestParameterException(MissingServletRequestParameterException ex) {
		log.info("---> 请求参数错误，缺少参数 :" + ex.getParameterName());
		return JsonResultConstant.create(601, "缺少参数" + ex.getParameterName());
	}
	/**
	 * 违反约束处理
	 */
	@ExceptionHandler(ConstraintViolationException.class)
	public JsonResultConstant constraintViolationException(ConstraintViolationException e) {
		Set<ConstraintViolation<?>> violations =  e.getConstraintViolations();
		Iterator<ConstraintViolation<?>> iter = violations.iterator();
		StringBuffer sb = new StringBuffer();
		while(iter.hasNext()) {
			ConstraintViolation<?> violation = iter.next();
			sb.append(violation.getMessage()).append(",");
		}
		log.info("---> 请求参数错误，违反参数约束 :" + sb.toString());
		return JsonResultConstant.create(602, sb.toString());
	}
	/**
	 * 请求参数类型转换错误异常处理
	 * @param ex
	 * @return
	 */
	@ExceptionHandler(MethodArgumentTypeMismatchException.class)
	public JsonResultConstant numberFormatException(MethodArgumentTypeMismatchException ex) {
		log.info("---> 参数格式不匹配：" + ex.getName());
		return JsonResultConstant.create(603, "---> 参数格式不匹配：" + ex.getName());
	}
}
